package org.smr.ministore.service.impl;

import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.blade.msg.ErrorCode;
import org.blade.service.base.AbstractService;
import org.blade.utils.Pager;

import org.smr.ministore.dao.AuthorityMapper;
import org.smr.ministore.dao.RoleMapper;
import org.smr.ministore.dao.UserMapper;
import org.smr.ministore.entities.Authority;
import org.smr.ministore.entities.Role;
import org.smr.ministore.entities.User;
import org.smr.ministore.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl extends AbstractService implements UserService {

	@Autowired
	private UserMapper mapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private AuthorityMapper authorityMapper;
	
	public int save(User entity) {
		this.saveAttatch(entity);
		if(!ObjectUtils.notEqual(entity.getOrganId(), null)){
			return ErrorCode.Business.Invalid_organId;
		}
		return mapper.insert(entity);
	}

	public int updateById(User id) {
		this.modifyAttach(id);
		return mapper.updateById(id);
	}

	@Transactional(readOnly = true)
	public User queryById(Long id) {
		return mapper.selectById(id);
	}

	public int deleteById(Long id) {
		return mapper.deleteById(id);
	}

	@Transactional(readOnly = true)
	public Pager<User> paginate( User entity, Long pageSize, Long pageNum) {

		Pager<User> pager = new Pager( pageSize, pageNum );
		List list  = mapper.pagination(entity, pager);
		pager.setEntities(list);
		return pager;
    }
	
	public int batchSave(List<User> entities) {
		return mapper.batchInsert(entities);
	}

	/**
	 * 根据用户名查询
	 * @param userName
	 * @return
	 */
	@Transactional(readOnly = true)
	public User queryByUserName( String userName){
		return mapper.selectByUserName(userName);
	}

	/**
	 * 根据用户名查询用户数
	 * @param userName
	 * @return
	 */
	@Transactional(readOnly = true)
	public Long getCountByUserName( String userName ){
		return mapper.getCountByUserName(userName);
	}

	@Transactional(readOnly = true)
	public List<Role> getRoleByUser(Long userId) {
		return roleMapper.selectByUser(userId);
	}

	@Transactional(readOnly = true)
	public List<Authority> getAuthoritiesByUser(Long userId) {
		return authorityMapper.selectByUser( userId );
	}

	@Transactional(readOnly = true)
	public User queryByMobile( String mobilePhone ) {

		return this.mapper.selectByMobile(mobilePhone);
	}

	/**
	 *
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Authority> getAuthoritiesByUserAndRoles(Long userId, Long... roleIds ){
		return authorityMapper.selectByUserAndRoles(userId, roleIds);
	}

}
